package com.jushu.storbox;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jushu.storbox.adapter.FileBrowserAllFileAdapter;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.manager.ActivityTaskManager;
import com.jushu.storbox.manager.DirectoryManager;
import com.jushu.storbox.util.LogUtil;

/**
 * <ol>
 * <li>&lt;uses-permission
 * android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt;</li>
 * <li>&lt;uses-permission
 * android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt;</li>
 * </ol>
 * 
 */

public class FileBrowserAllFileActivity extends BaseTitleActivity {
	/** ListView for all files */
	private ListView lv_all_files;

	private DirectoryManager dirManager;

	private ArrayList<File> datas;

	private File mCurrentDir;

	private FileBrowserAllFileAdapter adapter;

	private File rootDir;

	private boolean isFinish = false;

	/** activity TAG */
	private final static String LOG_TAG = "FileBrowserAllFileActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LogUtil.i(LOG_TAG, "onCreate()");
		isSDCardExist();
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_all_file);
		switchTypeTwo();
		setRightText(R.string.upload);
		ActivityTaskManager.getInstance().putActivity(LOG_TAG, FileBrowserAllFileActivity.this);
		init();
		findViews();
		setListeners();
		setAdapter();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		LogUtil.i(LOG_TAG, "onDestroy()");
		ActivityTaskManager.getInstance().removeActivity(LOG_TAG);
	}

	private void init() {
		dirManager = DirectoryManager.getInstance();
	}

	private void isSDCardExist() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath();
			rootDir = new File(rootPath);
		} else {
			rootDir = null;
			Toast.makeText(this, R.string.sdcard_not_find, Toast.LENGTH_LONG).show();
		}
	}

	private void findViews() {
		lv_all_files = (ListView) findViewById(R.id.lv_all_files);
	}

	private void setListeners() {
		lv_all_files.setOnItemClickListener(new OnItemClickListenerImpl());
	}

	@Override
	protected void onLeftClicked(View clickView) {
		if (mCurrentDir.equals(rootDir)) {
			// returnIcon.setVisibility(View.GONE);
			this.finish();
			// return;
		}
		browseTo(mCurrentDir.getParentFile(), null);
		if (null != adapter) {
			adapter.unCheckBox();
			adapter.getSelectedFiles().clear();
		}
		notifyDataSetChanged();
		super.onLeftClicked(clickView);
	}

	@Override
	protected void onRightClicked(View clickView) {
		if (!ShareDriveApplication.getInstance().getWifiController().getNetworkState()) {
			Toast.makeText(FileBrowserAllFileActivity.this, FileBrowserAllFileActivity.this.getString(R.string.allfile_search_is_not_vailible),
					Toast.LENGTH_SHORT).show();
		} else {
			Intent data = new Intent();
			Bundle bundle = new Bundle();
			bundle.putStringArrayList("resultUIL", adapter.getSelectedFiles());
			data.putExtra("result", bundle);
			setResult(MessageCode.UPLOAD_SELECT_FILE_RESULTCODE, data);
		}
		FileBrowserAllFileActivity.this.finish();
		super.onRightClicked(clickView);
	}

	private void setAdapter() {
		this.browseTo(rootDir, null);
		adapter = new FileBrowserAllFileAdapter(datas, lv_all_files, this);
		lv_all_files.setAdapter(adapter);
	}

	/**
	 * @param location
	 */
	private synchronized void browseTo(final File location, String[] mFilters) {

		if (null == rootDir) {
			Toast.makeText(this, R.string.sdcard_not_find, Toast.LENGTH_LONG).show();
			return;
		}

		if (null == location) {
			return;
		}

		if (location.equals(rootDir)) {
			// returnIcon.setVisibility(View.GONE);
			mCurrentDir = rootDir;
		} else {
			returnGroup.setVisibility(View.VISIBLE);
			if (!location.isDirectory()) {
				mCurrentDir = location.getParentFile();
				return;
			} else {
				mCurrentDir = location;
			}
		}
		if (mCurrentDir.equals(rootDir)) {
			setCurrentTitle(R.string.nav_file_txt);
		} else {
			setCurrentTitle(mCurrentDir.getName().compareTo("") == 0 ? mCurrentDir.getPath() : mCurrentDir.getName());
		}
		if (datas != null) {
			datas.clear();
		} else {
			datas = new ArrayList<File>();
		}
		datas.addAll(dirManager.getDirectoryListing(location, mFilters));
	}

	private class OnItemClickListenerImpl implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			File item = adapter.getItem(position);
			if (!item.isFile()) {
				browseTo(item, null);
				notifyDataSetChanged();
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:

			if (null == mCurrentDir) {
				return super.onKeyDown(keyCode, event);
			}

			if (mCurrentDir.equals(rootDir)) {
				// returnIcon.setVisibility(View.GONE);
				isFinish = true;
			} else {
				isFinish = false;
			}

			if (isFinish) {
				FileBrowserAllFileActivity.this.finish();
				return super.onKeyDown(keyCode, event);
			} else {
				browseTo(mCurrentDir.getParentFile(), null);
				notifyDataSetChanged();
				return false;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	private void notifyDataSetChanged() {
		if (null != adapter) {
			adapter.clearCacheState();
			// adapter.getIsSelected();
			adapter.notifyDataSetChanged();
		}
	}

}
